import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { LoginDto } from 'src/modules/background/login/dto/login.dto';
import { LoginVo } from 'src/modules/background/login/vo/login.vo';
import { UserEntity } from 'src/entity/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ToolsService } from 'src/tools/tools/tools.service';
import { CacheService } from 'src/tools/redis/redis.cache.service';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly toolsService: ToolsService,
    private readonly redisService: CacheService,
    private readonly jwtService: JwtService,
  ) {}
  async validateUser(email: string, pass: string): Promise<any> {
    const user = await this.userRepository.findOne({where:{email},select: ['username','email', 'password','passSalt']});
    const salt = user.passSalt; // 制作密码盐
    const passNew = this.toolsService.encryptPassword(pass, salt);
    if (user && user.password === passNew) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(login: LoginDto): Promise<LoginVo> {
    const { password, email } = login;
      // 1.先判断用户存在
      const result = await this.userRepository.findOne({where:{email},select:['password','passSalt','username','id','isSuper']});
      if (result) {
        const salt = result.passSalt; // 制作密码盐
        const hashPwd = this.toolsService.encryptPassword(password, salt);
        if (hashPwd === result.password) {
          const payload ={
            email:result.email,
            username:result.username,
            isSuper:result.isSuper,
            mobile:result.mobile,
            id:result.id,
          }
          const token = this.jwtService.sign(payload)
          await this.redisService.set(`user-token-${result.id}`, token, 7200 ); 
          return {
            token
          };
        } else {
          throw new HttpException('密码错误', HttpStatus.OK);
        }
      } else {
        throw new HttpException('邮箱错误', HttpStatus.OK);
      }
  }
}
